<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">销售登记</h1>
      <n-button @click="$router.back()">返回</n-button>
    </div>
    
    <n-card>
      <n-form ref="formRef" :model="formData" :rules="rules" label-placement="top">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-grid-item :span="12" label="支付方式" path="paymentMethod">
            <n-select v-model:value="formData.paymentMethod" :options="paymentOptions" placeholder="请选择支付方式" />
          </n-form-item-grid-item>
          
          <n-form-item-grid-item :span="12" label="备注">
            <n-input v-model:value="formData.remark" placeholder="选填" />
          </n-form-item-grid-item>
        </n-grid>
        
        <n-divider />
        
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
          <h3>商品明细</h3>
          <n-button type="primary" @click="handleAddItem">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
            添加商品
          </n-button>
        </div>
        
        <n-table :single-line="false">
          <thead>
            <tr>
              <th>商品名称</th>
              <th>单价</th>
              <th>库存</th>
              <th>数量</th>
              <th>小计</th>
              <th style="width: 100px;">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in formData.items" :key="index">
              <td>
                <n-select 
                  v-model:value="item.breadId" 
                  :options="breadOptions" 
                  placeholder="请选择商品"
                  filterable
                  @update:value="(value) => handleBreadChange(value, index)"
                />
              </td>
              <td>{{ item.price ? `¥${item.price}` : '-' }}</td>
              <td>{{ item.stock !== null ? item.stock : '-' }}</td>
              <td>
                <n-input-number 
                  v-model:value="item.quantity" 
                  :min="1" 
                  :max="item.stock"
                  placeholder="数量"
                  @update:value="calculateSubtotal(index)"
                />
              </td>
              <td>{{ item.subtotal ? `¥${item.subtotal.toFixed(2)}` : '-' }}</td>
              <td>
                <n-button size="small" type="error" @click="handleRemoveItem(index)">
                  <template #icon>
                    <n-icon><TrashOutline /></n-icon>
                  </template>
                  删除
                </n-button>
              </td>
            </tr>
          </tbody>
        </n-table>
        
        <n-divider />
        
        <div style="text-align: right; font-size: 18px; font-weight: 600; margin-bottom: 24px;">
          订单总额：<span style="color: #18a058;">¥{{ totalAmount }}</span>
        </div>
        
        <n-space justify="center">
          <n-button @click="$router.back()">取消</n-button>
          <n-button type="primary" @click="handleSubmit" :loading="submitting">提交订单</n-button>
        </n-space>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getBreadList } from '@/api/bread'
import { createOrder } from '@/api/sales'
import { 
  NCard, NForm, NFormItemGridItem, NGrid, NSelect, NInput, NDivider, NTable,
  NInputNumber, NButton, NIcon, NSpace, useMessage
} from 'naive-ui'
import { AddOutline, TrashOutline } from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

const formRef = ref(null)
const submitting = ref(false)
const breadList = ref([])

const formData = ref({
  paymentMethod: null,
  remark: '',
  items: []
})

const paymentOptions = [
  { label: '现金', value: '现金' },
  { label: '微信', value: '微信' },
  { label: '支付宝', value: '支付宝' }
]

const rules = {
  paymentMethod: { required: true, message: '请选择支付方式', trigger: 'change' }
}

const breadOptions = computed(() => {
  return breadList.value.map(bread => ({
    label: `${bread.name}（库存：${bread.stock}）`,
    value: bread.id,
    disabled: bread.stock <= 0
  }))
})

const totalAmount = computed(() => {
  const total = formData.value.items.reduce((sum, item) => {
    return sum + (parseFloat(item.subtotal) || 0)
  }, 0)
  return total.toFixed(2)
})

async function loadBreadList() {
  try {
    const res = await getBreadList()
    breadList.value = res.data
  } catch (error) {
    message.error(error.message || '加载商品列表失败')
  }
}

function handleAddItem() {
  formData.value.items.push({
    breadId: null,
    price: null,
    stock: null,
    quantity: 1,
    subtotal: 0
  })
}

function handleRemoveItem(index) {
  formData.value.items.splice(index, 1)
}

function handleBreadChange(breadId, index) {
  const bread = breadList.value.find(b => b.id === breadId)
  if (bread) {
    formData.value.items[index].price = bread.price
    formData.value.items[index].stock = bread.stock
    calculateSubtotal(index)
  }
}

function calculateSubtotal(index) {
  const item = formData.value.items[index]
  if (item.price && item.quantity) {
    item.subtotal = parseFloat((item.price * item.quantity).toFixed(2))
  }
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    
    if (formData.value.items.length === 0) {
      message.warning('请至少添加一个商品')
      return
    }
    
    // 验证所有商品都已选择
    const hasEmptyBread = formData.value.items.some(item => !item.breadId)
    if (hasEmptyBread) {
      message.warning('请选择所有商品')
      return
    }
    
    submitting.value = true
    
    const data = {
      paymentMethod: formData.value.paymentMethod,
      remark: formData.value.remark,
      items: formData.value.items.map(item => ({
        breadId: item.breadId,
        quantity: item.quantity
      }))
    }
    
    await createOrder(data)
    message.success('销售登记成功')
    router.push('/sales')
  } catch (error) {
    if (error.message) {
      message.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadBreadList()
  handleAddItem() // 默认添加一行
})
</script>

